package com.ruoyi.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.system.bo.ZhcaInformationAddBo;
import com.ruoyi.system.dto.OfficialAccountsAuthDto;
import com.ruoyi.system.service.IWechatService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.*;

/**
 * 公众号爬虫
 *
 * @author woo
 * @date 2021/7/29
 */
@Slf4j
public class OfficialAccountsReptile extends AbstractReptile<Map<String, Object>> {
	/**
	 * 公众号的ID
	 */
	private String fakeid;
	@Autowired
	private IWechatService wechatService;

	public OfficialAccountsReptile(Long state, String fakeid) {
		super(state);
		this.fakeid = fakeid;
	}

	@Override
	public Collection<Header> getDefaultHeaders() {
		OfficialAccountsAuthDto auth = getAuth();
		if (auth == null) {
			return Collections.emptyList();
		}
		List<Header> headers = new ArrayList<>();
		// 设置Cookie,只有token和Cookie是配套的
		headers.add(new BasicHeader("Cookie", auth.getCookie()));
		return headers;
	}

	public OfficialAccountsAuthDto getAuth() {
		return wechatService.getToken();
	}

	@Override
	public List<Map<String, Object>> getList() {
		CloseableHttpClient client = createHttpClient(true);
		List<Map<String, Object>> total = new ArrayList<>();
		int count = 5;
		int page = 1;
		while (true) {
			//2、封装请求参数
			List<BasicNameValuePair> list = new ArrayList<>();
			//查询
			list.add(new BasicNameValuePair("query", ""));
			//json格式化返回
			list.add(new BasicNameValuePair("f", "json"));
			//公众号标识
			list.add(new BasicNameValuePair("fakeid", this.fakeid));
			//查询的数量(天),即查多少天的文章,1代表昨天,2代表昨天+前天
			list.add(new BasicNameValuePair("count", count + ""));
			//查询最近
			list.add(new BasicNameValuePair("action", "list_ex"));
			list.add(new BasicNameValuePair("type", "9"));
			//中文
			list.add(new BasicNameValuePair("lang", "zh_CN"));
			//开始0,今天开始
			list.add(new BasicNameValuePair("begin", count * (page - 1) + ""));
			//ajax请求
			list.add(new BasicNameValuePair("ajax", "1"));
			//token信息
			list.add(new BasicNameValuePair("token", this.getAuth().getToken()));
			try {
				//3、转化参数
				String params = EntityUtils.toString(new UrlEncodedFormEntity(list, Consts.UTF_8));
				//4、创建HttpGet请求
				HttpGet httpGet = new HttpGet("https://mp.weixin.qq.com/cgi-bin/appmsg" + "?" + params);
				CloseableHttpResponse execute = client.execute(httpGet);
				HttpEntity entity = execute.getEntity();
				if (entity != null) {
					Map<String, Object> map = JsonUtils.parseMap(EntityUtils.toString(entity));
					List<Map<String, Object>> lists = (List<Map<String, Object>>) Convert.toList(map.get("app_msg_list"));
					if (CollUtil.isEmpty(lists)) {
						break;
					}
					total.addAll(lists);
					page++;
				}
			} catch (IOException e) {
				log.error(StrUtil.format("查询公众号列表失败:{}", e.getMessage(), e));
				break;
			}
		}
		return total;
	}

	@Override
	public String parseTitle(Map<String, Object> param) {
		return MapUtil.getStr(param, "title");
	}

	@Override
	public String loadData(Map<String, Object> param) {
//		CloseableHttpClient client = this.createHttpClient(false);
//		try {
//			CloseableHttpResponse execute = client.execute(new HttpGet(MapUtil.getStr(param, "link")));
//			HttpEntity entity = execute.getEntity();
//			if (entity != null) {
//				return EntityUtils.toString(entity);
//			}
//		} catch (IOException e) {
//			log.error(StrUtil.format("查询公众号详细失败:{}", e.getMessage(), e));
//		}
//		return null;
//		return MapUtil.getStr(param, "link");
		return null;
	}

	@Override
	public ZhcaInformationAddBo parseData(Map<String, Object> param, String data) {
//		if (StrUtil.isBlank(data)) {
//			return null;
//		}
		ZhcaInformationAddBo bo = new ZhcaInformationAddBo();
		bo.setTitle(MapUtil.getStr(param, "title"));
		bo.setPic(MapUtil.getStr(param, "cover"));
		bo.setContent(MapUtil.getStr(param, "link"));
//		Document document = Jsoup.parse(data.substring(data.indexOf("<!DOCTYPE html>")));
//		bo.setContent(document.selectFirst("#js_content").html());
		return bo;
	}
}
